package com.lwj.liwanjia.view.activity.personal.qian_bao;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.base.BaseActivity;
import com.lwj.liwanjia.bean.CenterBean05;
import com.lwj.liwanjia.bean.WxBean;
import com.lwj.liwanjia.config.URLConstant;
import com.lwj.liwanjia.impl.WxView;
import com.lwj.liwanjia.presenter.ChongzhiWxPayPresenter;
import com.lwj.liwanjia.utils.RxBus;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.view.activity.indent.PayCompleteActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.IOException;
import java.util.Map;

import constants.Constants;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by 001 on 2017/9/21.
 */

public class ChongZhiActivity extends BaseActivity implements View.OnClickListener, WxView {

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 0:
                    Toast.makeText(ChongZhiActivity.this, "数据有误", Toast.LENGTH_LONG).show();
                    break;

                case 1:

                    if (!TextUtils.isEmpty(zhiFuBaoKey)) {

                        //调起支付宝支付
                        initOkHttp02();
                    }

                    break;

                case 2:
                    Toast.makeText(ChongZhiActivity.this, "支付宝充值成功", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case 3:
                    Toast.makeText(ChongZhiActivity.this, "支付宝支付失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    private TextView tv_back;
    private TextView tv_title;
    private ImageView iv_zhiFuBaoQuan;//支付宝圈圈
    private ImageView iv_weiXinQuan;//微信圈圈
    private Button bt_sure;
    private EditText et_money;
    private TextView tv_yuEr;
    private int zhiFuType = 1;

    private String zhiFuBaoKey;//支付宝密钥
    private String token;
    private ChongzhiWxPayPresenter chongzhiWxPayPresenter;//微信支付
    private IWXAPI api;
    private Subscription subscribe;
    private String nowMoney;

    @Override
    protected void initView() {
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        tv_back = (TextView) findViewById(R.id.tv_left);
        tv_title = (TextView) findViewById(R.id.tv_title);
        iv_zhiFuBaoQuan = (ImageView) findViewById(R.id.iv_zhiFuBaoQuan);
        iv_weiXinQuan = (ImageView) findViewById(R.id.iv_weiXinQuan);
        bt_sure = (Button) findViewById(R.id.bt_sure);
        et_money = (EditText) findViewById(R.id.et_money);
        tv_yuEr = (TextView) findViewById(R.id.tv_yuEr);

        tv_back.setVisibility(View.VISIBLE);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("充值");

        tv_back.setOnClickListener(this);
        iv_zhiFuBaoQuan.setOnClickListener(this);
        iv_weiXinQuan.setOnClickListener(this);
        bt_sure.setOnClickListener(this);
        chongzhiWxPayPresenter = new ChongzhiWxPayPresenter(this);
        token = SpfUtils.getSpfUtils(this).getToken();
        Intent intent = getIntent();
        nowMoney = intent.getStringExtra("moneyCenter");
        tv_yuEr.setText("账号余额￥" + nowMoney + "元");
        subscribe = RxBus.getInstance().toObserverable(String.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                if (s.equals("支付完成")) {
                    finish();
                }
            }
        });
    }

    @Override
    protected void initData() {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_chong_zhi;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回
            case R.id.tv_left:
                finish();
                break;
            //支付宝圈圈
            case R.id.iv_zhiFuBaoQuan:
                zhiFuType = 1;
                //更改UI
                iv_zhiFuBaoQuan.setImageResource(R.mipmap.kuang_1);
                iv_weiXinQuan.setImageResource(R.mipmap.kuang);
                break;
            //微信圈圈
            case R.id.iv_weiXinQuan:
                zhiFuType = 2;
                //更改UI
                iv_zhiFuBaoQuan.setImageResource(R.mipmap.kuang);
                iv_weiXinQuan.setImageResource(R.mipmap.kuang_1);

                break;
            //确定
            case R.id.bt_sure:
                switch (zhiFuType) {
                    //支付宝
                    case 1:
                        String money = et_money.getText().toString().trim();
                        if (!TextUtils.isEmpty(money)) {
                            //判断money^(0|[1-9][0-9]*)$
                            String regex = "^[0-9]+(.[0-9]{1,2})?$";
                            boolean flag = money.matches(regex);
                            if (flag) {
                                //连网,获取数据
                                initOkHttp01(money);
                            } else {
                                Toast.makeText(ChongZhiActivity.this, "金额不合法", Toast.LENGTH_LONG).show();
                            }

                        } else {
                            Toast.makeText(ChongZhiActivity.this, "金额不能为空", Toast.LENGTH_LONG).show();
                        }

                        break;

                    //微信支付
                    case 2:
                        String money1 = et_money.getText().toString().trim();
                        if (!TextUtils.isEmpty(money1)) {
                            //判断money
                            String regex = "^[0-9]+(.[0-9]{1,2})?$";
                            boolean flag = money1.matches(regex);
                            if (flag) {
                                chongzhiWxPayPresenter.getChongzhiPayInfo(token, money1);
                            } else {
                                Toast.makeText(ChongZhiActivity.this, "金额不合法", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Toast.makeText(ChongZhiActivity.this, "金额不能为空", Toast.LENGTH_LONG).show();
                        }
                        break;
                }

                break;
        }
    }

    //连网,获取数据 支付宝
    private void initOkHttp01(String money) {

        String url = URLConstant.BASE_URL + "alipay/appDeposit";
        String token = SpfUtils.getSpfUtils(this).getToken();

        OkHttpClient mOkHttpClient = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("money", money)
                .add("token", token)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Call mCall = mOkHttpClient.newCall(request);
        mCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //Log.d("Tag", "分类数据获取失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //Log.d("Tag", "分类图数据获取成功");

                String result = null;

                try {
                    result = response.body().string();
                    //Log.d("Tag",result);
                } catch (Exception e) {

                }

                parse01(result);
            }
        });
    }

    //解析支付宝
    private void parse01(String result) {

        Gson gson = new Gson();
        CenterBean05 bean = gson.fromJson(result, CenterBean05.class);

        if (bean != null) {

            switch (bean.getState()) {

                case 0:
                    mHandler.sendEmptyMessage(0);
                    break;

                case 1:

                    zhiFuBaoKey = bean.getData().getAliAppPay();

                    mHandler.sendEmptyMessage(1);

                    break;
            }
        }
    }

    //调起支付宝支付
    private void initOkHttp02() {

        new Thread(new Runnable() {
            @Override
            public void run() {

                try {

                    PayTask alipay = new PayTask(ChongZhiActivity.this);
                    Map<String, String> resultMap = (alipay.payV2(zhiFuBaoKey, true));
                    String state = resultMap.get("resultStatus");
                    switch (state) {
                        case "9000":
                            mHandler.sendEmptyMessage(2);
                            break;
                        case "4000":
                            mHandler.sendEmptyMessage(3);
                            break;
                    }
                } catch (Exception e) {
                    Log.d("Tag", "请重试");
                    finish();
                }
            }
        }).start();
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(this, "支付有误", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getWxPayInfo(WxBean wxBean) {
        if (wxBean.getState() == 0) {
            Toast.makeText(this, "接口有误", Toast.LENGTH_SHORT).show();
        } else if (wxBean.getState() == 1) {
            WxBean.DataBean data = wxBean.getData();
            PayReq req = new PayReq();
            req.appId = data.getMsg().getAppid();
            req.partnerId = data.getMsg().getPartnerid();
            req.prepayId = data.getMsg().getPrepayid();
            req.nonceStr = data.getMsg().getNoncestr();
            req.timeStamp = String.valueOf(data.getMsg().getTimestamp());
            req.packageValue = data.getMsg().getPackageX();
            req.sign = data.getMsg().getSign();
            api.sendReq(req);
        }
    }

    @Override
    protected void onDestroy() {
        if (chongzhiWxPayPresenter != null) {
            chongzhiWxPayPresenter = null;
        }
        if (!subscribe.isUnsubscribed()) {
            subscribe.unsubscribe();
        }
        super.onDestroy();
    }
}
